<script setup>
import { ref, computed, onUnmounted } from 'vue'
import { wsManager } from '@/utils/websocket'

const myId = ref(localStorage.getItem('chat_my_id') || '')
const myName = ref(localStorage.getItem('chat_my_name') || '')
// 联系人与当前选中会话
const contacts = ref(JSON.parse(localStorage.getItem('chat_contacts') || '[]')) // [{id,name,unread}]
const currentPeerId = ref(localStorage.getItem('chat_peer_id') || '')
const currentPeerName = ref(localStorage.getItem('chat_peer_name') || '')
const messageInput = ref('')
const isConnected = ref(false)
// 每个会话独立消息历史：{ [peerId]: Message[] }
const convoMap = ref(JSON.parse(localStorage.getItem('chat_convos') || '{}'))
const logs = computed(() => convoMap.value[currentPeerId.value] || [])

let off = null

function connect() {
  if (!myId.value) {
    alert('请输入自己的ID')
    return
  }
  const name = myName.value || `用户${myId.value}`
  localStorage.setItem('chat_my_id', myId.value)
  localStorage.setItem('chat_my_name', name)
  if (currentPeerId.value) localStorage.setItem('chat_peer_id', currentPeerId.value)
  if (currentPeerName.value) localStorage.setItem('chat_peer_name', currentPeerName.value)

  wsManager.connect(String(myId.value), name)
  isConnected.value = true

  if (!off) {
    off = wsManager.onMessage((msg) => {
      // 仅展示聊天相关或系统相关信息
      if (msg?.type === 'chat') {
        const peer = msg.from
        if (!convoMap.value[peer]) convoMap.value[peer] = []
        convoMap.value[peer].push({
          time: msg.time || new Date().toLocaleTimeString(),
          from: `${msg.from_nickname || msg.from}`,
          to: `${myName.value || myId.value}`,
          content: msg.content,
          kind: 'in'
        })
        // 未读计数
        if (peer !== currentPeerId.value) {
          const c = contacts.value.find(c => c.id === peer)
          if (c) c.unread = (c.unread || 0) + 1
        }
        persist()
      } else if (msg?.type === 'system' || msg?.type === 'success' || msg?.type === 'error') {
        const peer = currentPeerId.value || 'system'
        if (!convoMap.value[peer]) convoMap.value[peer] = []
        convoMap.value[peer].push({ time: new Date().toLocaleTimeString(), content: msg.message, kind: 'system' })
        persist()
      } else if (typeof msg === 'string') {
        const peer = currentPeerId.value || 'system'
        if (!convoMap.value[peer]) convoMap.value[peer] = []
        convoMap.value[peer].push({ time: new Date().toLocaleTimeString(), content: msg, kind: 'text' })
        persist()
      }
    })
  }
}

function disconnect() {
  wsManager.disconnect()
  isConnected.value = false
  if (off) { off(); off = null }
}

function send() {
  if (!messageInput.value.trim()) return
  if (!currentPeerId.value) {
    alert('请输入对方ID')
    return
  }
  const ok = wsManager.sendTo(String(currentPeerId.value), messageInput.value.trim())
  if (ok) {
    if (!convoMap.value[currentPeerId.value]) convoMap.value[currentPeerId.value] = []
    convoMap.value[currentPeerId.value].push({
      time: new Date().toLocaleTimeString(),
      from: '我',
      to: currentPeerName.value || String(currentPeerId.value),
      content: messageInput.value.trim(),
      kind: 'out'
    })
    messageInput.value = ''
    persist()
  }
}

function persist() {
  localStorage.setItem('chat_contacts', JSON.stringify(contacts.value))
  localStorage.setItem('chat_convos', JSON.stringify(convoMap.value))
}

// 联系人操作
const newPeerId = ref('')
const newPeerName = ref('')
function addContact() {
  const id = newPeerId.value.trim()
  if (!id) return
  const name = newPeerName.value.trim() || id
  if (!contacts.value.find(c => c.id === id)) {
    contacts.value.push({ id, name, unread: 0 })
    persist()
  }
  newPeerId.value = ''
  newPeerName.value = ''
}

function selectContact(c) {
  currentPeerId.value = c.id
  currentPeerName.value = c.name
  c.unread = 0
  localStorage.setItem('chat_peer_id', currentPeerId.value)
  localStorage.setItem('chat_peer_name', currentPeerName.value)
  persist()
}

onUnmounted(() => {
  // 不强制断开，交由全局管理，避免影响其它页面
})
</script>

<template>
  <div class="chat-wrap">
    <h2 class="title">聊天</h2>

    <div class="top">
      <div class="me">
        <label>我的ID</label>
        <input v-model.trim="myId" placeholder="例如：user001" />
        <label>我的名称</label>
        <input v-model.trim="myName" placeholder="例如：张三" />
        <button @click="connect" :disabled="isConnected">连接</button>
        <button @click="disconnect" :disabled="!isConnected">断开</button>
        <span class="status" :class="{ on: isConnected }">{{ isConnected ? '已连接' : '未连接' }}</span>
      </div>
    </div>

    <div class="body">
      <aside class="sidebar">
        <div class="add">
          <input v-model.trim="newPeerId" placeholder="联系人ID" />
          <input v-model.trim="newPeerName" placeholder="联系人名称（可选）" />
          <button @click="addContact">添加</button>
        </div>
        <ul class="list">
          <li v-for="c in contacts" :key="c.id" :class="{ active: c.id === currentPeerId }" @click="selectContact(c)">
            <span class="name">{{ c.name || c.id }}</span>
            <span class="id">{{ c.id }}</span>
            <span v-if="c.unread" class="badge">{{ c.unread }}</span>
          </li>
        </ul>
      </aside>

      <section class="conversation">
        <div class="conv-title">{{ currentPeerName || currentPeerId || '请选择联系人' }}</div>
        <div class="log">
      <div v-for="(l, i) in logs" :key="i" :class="['item', l.kind]">
        <span class="time">[{{ l.time }}]</span>
        <template v-if="l.kind === 'in'">
          <span class="who">{{ l.from }} -> 我: </span>
          <span class="content">{{ l.content }}</span>
        </template>
        <template v-else-if="l.kind === 'out'">
              <span class="who">我 -> {{ l.to }}: </span>
          <span class="content">{{ l.content }}</span>
        </template>
        <template v-else>
          <span class="content">{{ l.content }}</span>
        </template>
      </div>
        </div>

        <div class="row">
          <input class="msg" v-model.trim="messageInput" placeholder="输入消息..." @keyup.enter="send" />
          <button @click="send" :disabled="!isConnected || !currentPeerId">发送</button>
        </div>
      </section>
    </div>
  </div>
</template>

<style scoped>
.chat-wrap { padding: 16px; max-width: 1100px; margin: 0 auto; }
.title { font-size: 20px; margin-bottom: 12px; }
.row { display: flex; align-items: center; gap: 8px; margin-bottom: 12px; }
.row input { padding: 6px 8px; border: 1px solid #ddd; border-radius: 6px; }
.row.gap button { margin-right: 8px; }
.status { margin-left: 8px; color: #999; }
.status.on { color: #16a34a; }
.body { display: grid; grid-template-columns: 300px 1fr; gap: 12px; }
.sidebar { border: 1px solid #eee; border-radius: 8px; padding: 8px; }
.add { display: flex; gap: 6px; margin-bottom: 10px; }
.list { list-style: none; padding: 0; margin: 0; }
.list li { display: flex; align-items: center; justify-content: space-between; padding: 8px; border-radius: 6px; cursor: pointer; }
.list li:hover { background: #f5f6f8; }
.list li.active { background: #eef2ff; }
.list .name { font-weight: 600; }
.list .id { color: #6b7280; font-size: 12px; margin-left: 6px; flex: 1; }
.badge { background: #ef4444; color: #fff; border-radius: 999px; padding: 0 6px; font-size: 12px; }
.conversation { border: 1px solid #eee; border-radius: 8px; padding: 8px; display: flex; flex-direction: column; }
.conv-title { font-weight: 600; margin-bottom: 6px; }
.log { border: 1px solid #eee; border-radius: 8px; padding: 8px; height: 360px; overflow: auto; background: #fafafa; }
.item { padding: 6px 8px; font-size: 14px; }
.item.in { color: #111827; }
.item.out { color: #1f2937; }
.item.system { color: #2563eb; }
.time { margin-right: 6px; color: #6b7280; }
.who { margin-right: 4px; font-weight: 600; }
.content { white-space: pre-wrap; word-break: break-word; }
.msg { flex: 1; }
button { padding: 6px 10px; border: 1px solid #ddd; background: white; border-radius: 6px; cursor: pointer; }
button:disabled { opacity: .5; cursor: not-allowed; }
</style>

